package com.dailyblue.example.springcloud.gateway.filter;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.example.springcloud.commons.config.JwtConfig;
import com.dailyblue.example.springcloud.commons.util.JsonResult;
import com.dailyblue.example.springcloud.commons.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;

//@Component
@Slf4j
public class TokenGlobalFilter implements GlobalFilter, Ordered {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        URI uri = exchange.getRequest().getURI();
        log.info("用户的请求是：{}", uri.getPath());
        if (uri.getPath().indexOf("login") != -1) {
            log.info("用户的请求是登陆");
            return chain.filter(exchange);
        }

        log.info("开始校验用户是否登陆");
        List<String> list = exchange.getRequest().getHeaders().get("token");
        if (list == null || list.size() == 0) {
            return error(exchange);
        }
        String token = list.get(0);
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            return error(exchange);
        }
        String id = JwtConfig.parseJWT(token).get("id").toString();
        String redisToken = stringRedisTemplate.opsForValue().get("TOKEN:" + id);
        if (!token.equals(redisToken)) {
            return error(exchange);
        }
        log.info("用户token:{}和redis的token:{}，一致", token, redisToken);
        return chain.filter(exchange);
    }

    private Mono<Void> error(ServerWebExchange exchange) {
        // 浏览器没有携带token
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应状态码
        response.setStatusCode(HttpStatus.resolve(403));
        // 设置返回格式
        response.getHeaders().set("ContentType", "application/json;charset=utf-8");
        // 设置返回的内容
        JsonResult result = ResultTool.fail(403, "用户没有登陆");
        String str = JSONArray.toJSONString(result);
        DataBuffer data = response.bufferFactory().wrap(str.getBytes(StandardCharsets.UTF_8));
        log.info("用户未携带token,{}", str);
        return response.writeWith(Mono.just(data));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
